package com.netty.nio;


import java.io.DataOutput;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.Iterator;
import java.util.Set;

public class NIOServer {
    public static void main(String[] args) throws IOException {
        //创建serversocketChannel
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        //获取一个selector
        Selector selector = Selector.open();
        //绑定一个端口6666,在服务器监听
        serverSocketChannel.socket().bind(new InetSocketAddress(6666));
        //设置为非阻塞
        serverSocketChannel.configureBlocking(false);
        //将serversocketchannel也要注册到selector中,关心的事件为OP_ACCEPT
        serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
        System.out.println("注册后的selectionkey 数量=" + selector.keys().size()); // 1
        //等待客户端连接
        while (true) {
            if(selector.select(1000) == 0) {//等待一秒
                System.out.println("服务器等待了1 秒,无连接,服务器不在等待");
                continue;
            }
            //如果返回的大于0 ,获取相关的selectionKey集合(也就是有事件发生的集合)
            Set<SelectionKey> selectionKeys = selector.selectedKeys();
            //通过selectionKey反向获取channel
            Iterator<SelectionKey> keyIterator = selectionKeys.iterator();
            System.out.println("注册后的selectionkey 数量=" + selector.keys().size()); //keys是指所有key不管有没有事件

            while (keyIterator.hasNext()) {
                //获取selectionKey
                SelectionKey selectionKey = keyIterator.next();
                //根据Key对应的channel发生的事件作对应的处理
                if (selectionKey.isAcceptable()){//表示有新的客户端连接
                    //给该客户端生产一个socketChannel
                    SocketChannel socketChannel = serverSocketChannel.accept();//accept()方法是阻塞的,但是现在已经有连接来了
                    System.out.println("客户端连接成功 生成了一个 socketChannel " + socketChannel.hashCode());
                    //将  SocketChannel 设置为非阻塞
                    socketChannel.configureBlocking(false);
                    //将socketChannel也注册到selector上,关注的事件是OP_READ,并关联一个Buffer,大小是1024
                    socketChannel.register(selector, SelectionKey.OP_READ, ByteBuffer.allocate(1024));
                }else if (selectionKey.isReadable()){//发生OP_READ
                    //根据Key对应的channel发生的事件作对应的处理
                    //反向获取socketChannel
                    SocketChannel channel = (SocketChannel) selectionKey.channel();
                    //获取到该channel关联的buffer
                    ByteBuffer byteBuffer = (ByteBuffer) selectionKey.attachment();
                    //将当前的channel的数据读到buffer里面
                    channel.read(byteBuffer);
                    System.out.println("客户端发送了数据+" + new String(byteBuffer.array()));
                }
                //手动从集合中移除当前的selectionKey,防止重复操作
                keyIterator.remove();
            }
        }

    }
}
